import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  LinearProgress,
  Stack,
  Chip,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  IconButton,
  Grid,
  Alert,
  CircularProgress
} from '@mui/material';
import {
  Timeline,
  TimelineItem,
  TimelineSeparator,
  TimelineConnector,
  TimelineContent,
  TimelineDot,
  TimelineOppositeContent
} from '@mui/lab';
import {
  CheckCircle as CheckCircleIcon,
  Event as EventIcon,
  PhotoCamera as PhotoCameraIcon,
  LocationOn as LocationOnIcon,
  AccessTime as AccessTimeIcon,
  Close as CloseIcon
} from '@mui/icons-material';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { useActivities } from '../contexts/ActivityContext';
import axios from 'axios';
import { useAuth } from '../contexts/AuthContext';
import { useResources } from '../contexts/ResourceContext';

function CheckInModule() {
  const { activities, loading, error, checkInActivity } = useActivities();
  const { token } = useAuth();
  const { userActivities, fetchUserActivities } = useResources();
  const [selectedActivity, setSelectedActivity] = useState(null);
  const [checkInDialogOpen, setCheckInDialogOpen] = useState(false);
  const [note, setNote] = useState('');
  const [images, setImages] = useState([]);
  const [imagePreview, setImagePreview] = useState([]);
  const [location, setLocation] = useState(null);
  const [locationLoading, setLocationLoading] = useState(false);
  const [checkInLoading, setCheckInLoading] = useState(false);
  const [checkInError, setCheckInError] = useState('');
  const [checkInSuccess, setCheckInSuccess] = useState('');

  // 获取当前位置
  const getCurrentLocation = async () => {
    if (!navigator.geolocation) {
      setCheckInError('您的浏览器不支持地理位置功能');
      return;
    }

    setLocationLoading(true);
    try {
      const position = await new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 0
        });
      });
      
      setLocation([position.coords.longitude, position.coords.latitude]);
      setLocationLoading(false);
    } catch (error) {
      console.error('获取位置失败:', error);
      setCheckInError('无法获取您的位置，请确保已授权位置权限');
      setLocationLoading(false);
    }
  };

  // 处理图片上传
  const handleImageChange = (e) => {
    const files = Array.from(e.target.files);
    setImages(files);
    
    // 创建预览
    const previews = files.map(file => URL.createObjectURL(file));
    setImagePreview(previews);
  };

  // 打开打卡对话框
  const openCheckInDialog = (activity) => {
    setSelectedActivity(activity);
    setCheckInDialogOpen(true);
    setNote('');
    setImages([]);
    setImagePreview([]);
    setLocation(null);
    setCheckInError('');
    getCurrentLocation();
  };

  // 提交打卡
  const handleSubmit = async () => {
    if (!selectedActivity) return;

    try {
      setCheckInLoading(true);
      setCheckInError('');

      const formData = new FormData();
      formData.append('note', note);
      
      // 添加位置信息
      if (location) {
        formData.append('location', JSON.stringify(location));
      }
      
      // 添加图片
      images.forEach(image => {
        formData.append('images', image);
      });

      const response = await axios.post(
        `/api/resources/${selectedActivity._id}/checkin`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${token}`
          }
        }
      );

      console.log('打卡响应:', response.data);
      setCheckInSuccess('打卡成功！');
      setCheckInDialogOpen(false);
      
      // 重要：更新活动数据
      await fetchUserActivities();
      
      // 更新当前选中活动的进度
      if (userActivities) {
        const updatedActivity = userActivities.find(a => a._id === selectedActivity._id);
        if (updatedActivity) {
          setSelectedActivity(updatedActivity);
        }
      }
      
      setTimeout(() => {
        setCheckInSuccess('');
      }, 3000);
    } catch (err) {
      console.error('打卡失败:', err);
      setCheckInError(err.response?.data?.message || '打卡失败，请稍后重试');
    } finally {
      setCheckInLoading(false);
    }
  };

  // 格式化日期
  const formatDate = (date) => {
    if (!date) return '';
    return format(new Date(date), 'yyyy年MM月dd日 HH:mm', { locale: zhCN });
  };

  return (
    <Box>
      <Typography variant="h6" gutterBottom>
        我的打卡活动
      </Typography>

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
          <CircularProgress />
        </Box>
      ) : error ? (
        <Alert severity="error" sx={{ my: 2 }}>
          {error}
        </Alert>
      ) : activities && activities.length > 0 ? (
        <>
          {/* 活动卡片列表 */}
          <Grid container spacing={2} sx={{ mb: 3 }}>
            {activities.map((activity) => (
              <Grid item xs={12} sm={6} md={4} key={activity._id}>
                <Card>
                  <CardContent>
                    <Typography variant="h6" gutterBottom>
                      {activity.title}
                    </Typography>
                    
                    <Box sx={{ mt: 2, mb: 1 }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
                        <Typography variant="body2" color="text.secondary">
                          进度
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          {Math.round(activity.progress)}%
                        </Typography>
                      </Box>
                      <LinearProgress 
                        variant="determinate" 
                        value={activity.progress} 
                        sx={{ height: 8, borderRadius: 4 }}
                      />
                    </Box>
                    
                    <Stack direction="row" spacing={1} sx={{ mt: 2, flexWrap: 'wrap', gap: 0.5 }}>
                      <Chip 
                        size="small" 
                        label={`${activity.checkins?.length || 0}/${activity.checkInRequired} 次打卡`}
                        color="primary"
                        variant="outlined"
                      />
                      <Chip 
                        size="small" 
                        label={`剩余 ${activity.remainingDays || 0} 天`}
                        color={activity.remainingDays < 3 ? "error" : "default"}
                      />
                    </Stack>
                  </CardContent>
                  
                  <Box sx={{ px: 2, pb: 2 }}>
                    <Button 
                      variant="contained" 
                      fullWidth
                      onClick={() => openCheckInDialog(activity)}
                      disabled={activity.progress >= 100}
                    >
                      {activity.progress >= 100 ? '已完成' : '打卡'}
                    </Button>
                  </Box>
                </Card>
              </Grid>
            ))}
          </Grid>

          {/* 打卡历史时间线 */}
          <Typography variant="h6" gutterBottom sx={{ mt: 4 }}>
            打卡历史
          </Typography>
          
          <Timeline position="alternate">
            {activities.flatMap(activity => 
              (activity.checkins || []).map((checkin, index) => (
                <TimelineItem key={`${activity._id}-${index}`}>
                  <TimelineOppositeContent color="text.secondary">
                    {formatDate(checkin.date)}
                  </TimelineOppositeContent>
                  <TimelineSeparator>
                    <TimelineDot color="success">
                      <CheckCircleIcon />
                    </TimelineDot>
                    <TimelineConnector />
                  </TimelineSeparator>
                  <TimelineContent>
                    <Typography variant="body1" component="span">
                      {activity.title}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {checkin.note || '无备注'}
                    </Typography>
                  </TimelineContent>
                </TimelineItem>
              ))
            )}
          </Timeline>
        </>
      ) : (
        <Alert severity="info" sx={{ my: 2 }}>
          您还没有参与需要打卡的活动，快去社区页面参与吧！
        </Alert>
      )}

      {/* 打卡对话框 */}
      <Dialog 
        open={checkInDialogOpen} 
        onClose={() => !checkInLoading && setCheckInDialogOpen(false)}
        fullWidth
        maxWidth="sm"
      >
        <DialogTitle>
          活动打卡
          {selectedActivity && (
            <Typography variant="subtitle1" color="text.secondary">
              {selectedActivity.title}
            </Typography>
          )}
          <IconButton
            aria-label="close"
            onClick={() => setCheckInDialogOpen(false)}
            sx={{ position: 'absolute', right: 8, top: 8 }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        
        <DialogContent>
          {checkInSuccess && (
            <Alert severity="success" sx={{ mb: 2 }}>
              {checkInSuccess}
            </Alert>
          )}
          
          {checkInError && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {checkInError}
            </Alert>
          )}
          
          <Stack spacing={3} sx={{ mt: 1 }}>
            <Box>
              <Typography variant="subtitle2" gutterBottom>
                位置信息
              </Typography>
              
              <Button
                variant="outlined"
                startIcon={<LocationOnIcon />}
                onClick={getCurrentLocation}
                disabled={locationLoading}
                sx={{ mb: 1 }}
              >
                {locationLoading ? '获取中...' : '获取当前位置'}
              </Button>
              
              {location ? (
                <Typography variant="body2" color="success.main">
                  位置信息已获取
                </Typography>
              ) : (
                <Typography variant="body2" color="error">
                  未获取位置信息
                  <Button 
                    size="small" 
                    onClick={getCurrentLocation}
                    sx={{ ml: 1 }}
                  >
                    重试
                  </Button>
                </Typography>
              )}
            </Box>
            
            <TextField
              label="打卡记录"
              multiline
              rows={4}
              value={note}
              onChange={(e) => setNote(e.target.value)}
              fullWidth
              placeholder="记录一下此次打卡的心得体会..."
            />
            
            <Box>
              <input
                accept="image/*"
                id="check-in-image-upload"
                type="file"
                multiple
                onChange={handleImageChange}
                style={{ display: 'none' }}
              />
              <label htmlFor="check-in-image-upload">
                <Button
                  variant="outlined"
                  component="span"
                  startIcon={<PhotoCameraIcon />}
                >
                  上传图片
                </Button>
              </label>
              
              {imagePreview.length > 0 && (
                <Grid container spacing={1} sx={{ mt: 1 }}>
                  {imagePreview.map((src, index) => (
                    <Grid item xs={4} key={index}>
                      <img 
                        src={src} 
                        alt={`预览 ${index + 1}`} 
                        style={{ width: '100%', borderRadius: 4 }}
                      />
                    </Grid>
                  ))}
                </Grid>
              )}
            </Box>
          </Stack>
        </DialogContent>
        
        <DialogActions>
          <Button 
            onClick={() => setCheckInDialogOpen(false)}
            disabled={checkInLoading}
          >
            取消
          </Button>
          <Button
            variant="contained"
            onClick={handleSubmit}
            disabled={checkInLoading || !location}
            startIcon={checkInLoading ? <CircularProgress size={16} /> : <CheckCircleIcon />}
          >
            {checkInLoading ? '提交中...' : '确认打卡'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 成功提示 */}
      {checkInSuccess && (
        <Alert 
          severity="success" 
          sx={{ 
            position: 'fixed', 
            bottom: 16, 
            right: 16, 
            zIndex: 9999 
          }}
          onClose={() => setCheckInSuccess('')}
        >
          {checkInSuccess}
        </Alert>
      )}
    </Box>
  );
}

export default CheckInModule; 